package com.yitiao.multithread.case01;

/**
 * <h3>守护线程案例</h3>
 * <p>非守护线程 testThread 的内部一直在执行 while 循环，导致 main 线程无法结束执行</p>
 * <p>守护线程具有在JVM退出的时候也自我销毁的特点</p>
 */
public class DaemonThreadDemo {

    public static void main(String[] args) throws InterruptedException {
        // 监听当前 JVM 是否退出
        Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("jvm exit success!! ")));

        Thread testThread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(2000);
                    System.out.println("thread still running ....");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        testThread.setDaemon(true); // 设置为守护线程
        testThread.start();
    }
}
